package com.pay.ioopos.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.dongqing.payreport.PayReport;
import com.dongqing.payreport.PayReport.ReportCallBack;
import com.pay.ioopos.Utils;
import com.pay.ioopos.service.ReportService;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class ReportReceiver extends BroadcastReceiver {
    private Handler handler = new Handler();
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        if (!ReportService.isSdkInited()) {
            //showToast("微信SDK：未初始化，不上报");
            return;
        }
        new Thread(() -> {
            if (null == Looper.myLooper()) {
                Looper.prepare();
            }
            try {
                reportData(intent);
            } catch (Exception e) {
                Log.w(TAG, "微信SDK数据上报异常", e);
                showToast("微信SDK：" + e.getLocalizedMessage());
            }
        }).start();

    }

    private void reportData(Intent intent) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", intent.getStringExtra("out_trade_no"));
        map.put("transaction_id", intent.getStringExtra("transaction_id"));
        PayReport.getInstance(context).reportData(map, new ReportCallBack() {

            @Override
            public void Success(Call call, String json) {
                try {
                    JSONObject obj = new JSONObject(json);
                    obj = obj.optJSONObject("data");
                    if (null == obj) {
                        showToast("微信SDK：" + json);
                    } else if (!obj.optString("return_code").equals("SUCCESS")) {
                        showToast("微信SDK：" + obj.optString("return_msg"));
                    }
                } catch (JSONException e) {
                    Log.w(TAG, "微信SDK数据上报异常：", e);
                    showToast("微信SDK：" + e.getMessage());
                }
            }

            @Override
            public void Failed(String msg) {
                showToast("微信SDK-FAIL：" + msg);
            }
        });
    }

    private void showToast(String msg) {
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        handler.post(() -> Toast.makeText(context, msg, Toast.LENGTH_SHORT).show());
    }
}
